package cn.huapu.power.energy.util.token;


import cn.huapu.power.energy.bean.SysUser;
import cn.huapu.power.energy.ex.ErrorCodesException;
import cn.huapu.power.energy.service.SysUserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器验证token
 */
@Configuration
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String authHeader = request.getHeader("token");
        SysUser user = (SysUser) request.getSession().getAttribute("user");
        if (authHeader == null || !authHeader.startsWith("Bearer:")) {
            throw new ErrorCodesException("token错误",ErrorCodesException.LOGIN_ERR);
        }
        else {
        	if(user != null && user.getPkid() != null) {
        		return true;
        	}
        }
        try {
        	//取得token
            String token = authHeader.substring(7);
            //验证token
            Claims claims = JwtUtil.checkToken(token); 
            String uId =  (String)claims.get("userId");
            if(uId != null) {
            	user = userService.get(Integer.parseInt(uId));
            	if(user != null && user.getPkid() != null) {
            		request.getSession().setAttribute("user",user);
            		return true;
            	}
            }
			
		} catch (Exception e) {			
		}        
        throw new ErrorCodesException("Token 有误，请先登录",ErrorCodesException.LOGIN_ERR);       

    }



    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }

}
